//
//  LyricLineView.swift
//  一行歌词View
//
//  Created by smile on 2019/6/29.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

class LyricLineView: BaseView {

    /// 这一行歌词数据
    var data:LyricLine?
    
    /// 是否选中
    var isSelected = false
    
    /// 播放进度
    var progress:Float = 0
    
    /// 是否是精确到字的歌词
    var isAccurate = false
    
    /// 已经播放过的宽度
    var playedLyricWidth:CGFloat = 0
    
    
    /// 绘制
    /// 相当于Android中View控件的onDraw
    ///
    /// - Parameter rect: <#rect description#>
    override func draw(_ rect: CGRect) {
        //如果没有歌词就返回
        if data == nil {
            return
        }
        
        //获取系统字体
        let font = UIFont.systemFont(ofSize: 18)
        
        //设置字体大小
        var attributes:[NSAttributedString.Key:Any] = [NSAttributedString.Key.font:font]
        
        //获取到歌词
        let wordString = data!.data
        
        //将Swift中的String转为NSString
        let wordStringNSString = wordString! as NSString
        
        //获取歌词的宽高
        let size = computerSize(wordStringNSString,attributes)
        
        //计算绘制文本的位置
        let x = (frame.width - size.width)/2
        let y = (frame.height - size.height)/2
        
        //创建Point
        //CG:Core Graphics
        let point = CGPoint(x: x, y: y)
        
        //获取绘制上下文
        let context = UIGraphicsGetCurrentContext()!
        
        //保存状态
        context.saveGState()
        
        if isAccurate {
            //精确到字的歌词
            
            //绘制背景文字
            
            //创建一个frame
            //他正好和歌词宽高一样
            let frame = CGRect(x: point.x, y: point.y, width: size.width, height: size.height)
            
            //裁剪矩形
            context.clip(to: frame)
            
            //设置绘制颜色
            attributes[NSAttributedString.Key.foregroundColor] = UIColor.lightGray
            
            //绘制背景文字
            wordStringNSString.draw(at: point, withAttributes: attributes)
            
            if isSelected {
                //绘制高亮文字
                
                //获取当前时间点对应该行歌词第几个字
                let lyricCurrentWordIndex = LyricUtil.getWordIndex(data!,progress)
                
                if lyricCurrentWordIndex == -1 {
                    //当前行已经播放完这一句歌词了
                    playedLyricWidth = size.width
                }else {
                    //当前行没有播放完
                    
                    //所以说要计算播放时间
                    
                    //获取当前字已经唱过的时间
                    let wordPlayedTime = LyricUtil.getWordPlayedTime(data!,progress)
                    
                    //获取当前时间前面的字
                    let beforeText = data!.data.substring(toIndex: lyricCurrentWordIndex)
                    
                    //获取前面文字的宽度
                    let beforeTextSize = computerSize(beforeText as NSString, attributes)
                    
                    //获取当前字
                    let currentWord = data!.words![lyricCurrentWordIndex]
                    
                    //计算出当前字的宽
                    
                    //可以能大家觉得
                    //字宽度都是一定的
                    //但要考虑英文所以要算
                    let currentWordSize = computerSize(currentWord as! NSString, attributes)
                    
                    //当前字已经播放的宽度
                    
                    //计算方法：
                    //例如：当前字宽度为100px
                    //当前字持续时间为50秒
                    //那么 1秒宽度=当前字宽度/当前字持续时间
                    //已经播放的宽度=1秒宽度*已经播放的时间
                    
                    //当前字持续时间
                    let currentWordDuration = data!.wordDurations![lyricCurrentWordIndex]
                    
                    //当前字已经播放的宽度
                    let currentWordPlayedWidth = currentWordSize.width/CGFloat(currentWordDuration)*CGFloat(wordPlayedTime)
                    
                    //计算当前行播放宽度
                    playedLyricWidth = beforeTextSize.width+currentWordPlayedWidth
                    
                    print("LyricLineView draw:\(beforeText),\(beforeTextSize.width),\(wordPlayedTime),\(currentWordPlayedWidth),\(playedLyricWidth)")
                }
                
                //选中的矩形
                var selectedRect = frame
                selectedRect.size.width = playedLyricWidth
                
                //裁剪矩形
                context.clip(to: selectedRect)
                
                //设置选中颜色
                attributes[NSAttributedString.Key.foregroundColor]=UIColor(hex: COLOR_PRIMARY)
                
                //绘制文本
                wordStringNSString.draw(at: point, withAttributes: attributes)
            }
        } else {
            //精确到行的歌词
            
            //判断是否选中歌词了
            if isSelected {
                //选中了
                
                //主色调
                attributes[NSAttributedString.Key.foregroundColor] = UIColor(hex: COLOR_PRIMARY)
            } else {
                //未选中
                
                //默认颜色
                attributes[NSAttributedString.Key.foregroundColor] = UIColor.lightGray
            }
            
            //绘制歌词文本
            wordStringNSString.draw(at: point, withAttributes: attributes)
            
        }
        
        //恢复上下文
        context.restoreGState()
    }
    
    /// 计算NSString宽高
    ///
    /// - Parameter data: <#data description#>
    /// - Returns: <#return value description#>
    func computerSize(_ data:NSString,_ attributes:[NSAttributedString.Key:Any]) -> CGSize {
        //获取option
        let option = NSStringDrawingOptions.usesLineFragmentOrigin
        
        //计算歌词的frame
        let rect = data.boundingRect(with: frame.size, options: option, attributes: attributes, context: nil)
        
        //创建Size返回
        return CGSize(width: rect.width, height: rect.height)
    }
    
    /// 设置播放进度
    ///
    /// - Parameter progress: <#progress description#>
    func show(_ progress:Float)  {
        self.progress = progress
        
        //print("LyricLineView:\(data?.data),\(progress)")
    }
}
